package com.lhoverc.service.apply.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.lhoverc.mapper.ApplyMapper;
import com.lhoverc.mapper.UserMapper;
import com.lhoverc.mapper.VisitorMapper;
import com.lhoverc.pojo.PageBean;
import com.lhoverc.pojo.Result;
import com.lhoverc.pojo.VO.AdminApplyVO;
import com.lhoverc.pojo.VO.ApplyDataVO;
import com.lhoverc.pojo.VO.TodayApplyVO;
import com.lhoverc.pojo.dto.AddApplyDto;
import com.lhoverc.pojo.dto.InvitationDto;
import com.lhoverc.pojo.dto.SendInvitationCodeDto;
import com.lhoverc.pojo.entity.ApplyEntity;
import com.lhoverc.pojo.entity.VisitorEntity;
import com.lhoverc.service.apply.ApplyService;
import com.lhoverc.utils.MailMsg;
import jakarta.mail.MessagingException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: LiCheng
 * @CreateTime: 2025-04-16
 * @Description:
 * @Version: 1.0
 */
@Service
@Slf4j
public class ApplyServiceImpl implements ApplyService {
    @Autowired
    private VisitorMapper visitorMapper;
    @Autowired
    private ApplyMapper applyMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private MailMsg mailMsg;

    @Override
    public Result check(InvitationDto invitationDto) {

        //查询访客id
        Integer visitorId = visitorMapper.getIdByNameAndEmail(invitationDto.getVisitorName(), invitationDto.getVisitorEmail());
        //查询业主id
        ApplyEntity applyEntity = applyMapper.getApply(visitorId, invitationDto.invitationCode);
        //查询用户姓名
        String username = userMapper.getUsernameById(applyEntity.getUserId());
        if (username.equals(invitationDto.getUserName()))
            return Result.success(applyEntity);
        return Result.error("信息有误");
    }

    @Override
    public void pass(ApplyEntity applyEntity) {
        applyMapper.updateStateToArrive(applyEntity);
    }

    @Override
    public List<TodayApplyVO> getApplyById(Integer id) {
        List<TodayApplyVO> todayApplyVOList = new ArrayList<>();
        List<ApplyEntity> applyEntityList = applyMapper.getApplyById(id);
        for (ApplyEntity applyEntity : applyEntityList) {
            TodayApplyVO todayApplyVO = new TodayApplyVO();
            BeanUtils.copyProperties(applyEntity, todayApplyVO);
            todayApplyVO.setVisitorName(visitorMapper.getNameById(applyEntity.getVisitorId()));
            todayApplyVOList.add(todayApplyVO);
        }
        return todayApplyVOList;
    }

    @Override
    public void allowApply(List<Integer> ids) {
        applyMapper.updateState(ids, 2);
    }

    @Override
    public void refuseApply(List<Integer> ids) {
        applyMapper.updateState(ids, 4);
    }

    @Override
    public List<ApplyDataVO> getApplyData(Integer userId, String visitorName, Integer state, LocalDateTime startTime, LocalDateTime endTime) {
        List<ApplyDataVO> ApplyDataVOList = new ArrayList<>();
        List<ApplyEntity> applyEntityList = applyMapper.getApplyData(userId, state, startTime, endTime);
        for (ApplyEntity applyEntity : applyEntityList) {
            ApplyDataVO ApplyDataVO = new ApplyDataVO();
            BeanUtils.copyProperties(applyEntity, ApplyDataVO);
            String Name = visitorMapper.getNameByIdAndName(applyEntity.getVisitorId(), visitorName);
            if (Name != null && !Name.equals("")) {
                ApplyDataVO.setVisitorName(Name);
                ApplyDataVOList.add(ApplyDataVO);
            }
        }
        return ApplyDataVOList;
    }

    @Override
    public List<ApplyDataVO> getAllTodayApply() {
        LocalDateTime today = LocalDateTime.now();
        List<ApplyDataVO> applyDataVOList = applyMapper.getAllTodayApply(today);
        return applyDataVOList;
    }

    @Override
    public PageBean getAllApply(String searchKeyword, Integer statusKeyword,
                                LocalDateTime startTime, LocalDateTime endTime,
                                Integer page, Integer pageSize) {
        // 1. 设置分页参数
        PageHelper.startPage(page, pageSize);

        // 2. 执行查询（包含所有过滤条件）
        List<AdminApplyVO> voList = applyMapper.getAllApply(searchKeyword, statusKeyword, startTime, endTime);

        // 4. 获取分页信息
        PageInfo<AdminApplyVO> pageInfo = new PageInfo<>(voList);

        // 5. 返回正确分页结果
        return new PageBean(pageInfo.getTotal(), voList);
    }

    @Override
    public void addApply(AddApplyDto addApplyDto) throws MessagingException {

        ApplyEntity applyEntity = new ApplyEntity();
        VisitorEntity visitorEntity = new VisitorEntity();
        SendInvitationCodeDto sendInvitationCodeDto = new SendInvitationCodeDto();

        BeanUtils.copyProperties(addApplyDto, sendInvitationCodeDto);
        BeanUtils.copyProperties(addApplyDto, visitorEntity);
        BeanUtils.copyProperties(addApplyDto, applyEntity);

        Integer visitorId = visitorMapper.getIdByNameAndEmail(visitorEntity.getVisitorName(), visitorEntity.getVisitorEmail());
        if (visitorId == null) {
            visitorEntity.setCreateTime(LocalDateTime.now());
            visitorEntity.setUpdateTime(LocalDateTime.now());
            visitorMapper.insertVisitor(visitorEntity);
            applyEntity.setVisitorId(visitorEntity.getId());
        } else {
            applyEntity.setVisitorId(visitorId);
        }

        sendInvitationCodeDto.setUsername(userMapper.getUsernameById(applyEntity.getUserId()));
        applyEntity.setInvitationCode(mailMsg.sendInvitationCode(sendInvitationCodeDto));
        applyMapper.insertApply(applyEntity);
    }

    @Override
    public void updateApply(ApplyDataVO applyDataVO) {
        applyMapper.updateApply(applyDataVO);
    }

    @Override
    public void deleteApply(List<Integer> ids) {
        applyMapper.delete(ids);
    }

    @Override
    public List<ApplyEntity> getApply() {
        List<ApplyEntity> applyEntityList = applyMapper.getApplyNoParams();
        return applyEntityList;
    }
}
